//
//  EditHeaterInstallationTypeView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/7/27.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa

class EditHeaterInstallationTypeView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    //
    let installationTypeView = HeaterInstallationTypeView()
    let saveBtn = OperationButton(R.string.localizable.save())
    var saveBtnClosure: (()->Void)?
    
    override func setUpView(){
        self.backgroundColor = .white
        //增加scrollview，处理输入框被键盘遮挡的问题
        let scrollView = DIYScrollView()
        scrollView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom).offset(-20)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom).offset(Constant.BottomMargin)
        }
        
        let contentBackView = UIView()
        scrollView.addSubview(contentBackView)
        contentBackView.snp.makeConstraints { make in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        contentBackView.addSubview(installationTypeView)
        installationTypeView.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //save btn
        self.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom).offset(Constant.BottomMargin)
            make.left.right.equalTo(installationTypeView)
            make.height.equalTo(OperationButton.height)
        }
        saveBtn.addTarget(self, action: #selector(saveBtnClick), for: UIControl.Event.touchUpInside)
        
    }
    func setData(_ model: InstallationTypeViewModel){
        self.installationTypeView.setData(model,editFlag: true)
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //1.installation type
        let otherOrReplaceSolarValid = self.installationTypeView.viewModel.rx.observe(String.self, "installation_type_value").map({
            let data = $0 ?? ""
            if data != "" {
                if $0 == HeaterInstallationTypeValue.ReplacedSolarWarterHeater.rawValue || $0 == HeaterInstallationTypeValue.Other.rawValue{
                    return true
                }else{
                    return false
                }
            }else{
                return false
            }
            
        }).share(replay: 1)
        //2.additianal details不能为空（other，replace solar water heater）
        let additionalForOtherOrReplaceSolarValid = self.installationTypeView.viewModel.rx.observe(String.self, "additional_upgrade_system_details").map({
            if Tool().isValidAddtionalInfo(($0 ?? "")){
                return true
            }else{
                return false
            }
        }).share(replay: 1)
        //3.additianal details可以为空（除了other，replace solar water heater意外）
        let additionalForOtherValid = self.installationTypeView.viewModel.rx.observe(String.self, "additional_upgrade_system_details").map({
            let text = ($0 ?? "")
            if text == ""{
                return true
            }else{
                if Tool().isValidAddtionalInfo(text){
                    return true
                }else{
                    return false
                }
            }
        }).share(replay: 1)
        let everythingValid = Observable.combineLatest(
            otherOrReplaceSolarValid,
            additionalForOtherValid,
            additionalForOtherOrReplaceSolarValid
        ) {
            if ($0 && $2) || (!$0 && $1) {
                return true
            }
            return false
        }
        .share(replay: 1)
        everythingValid.subscribe {[weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.saveBtn.enableBtn()
            }else{
                strongSelf.saveBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
    @objc func saveBtnClick(){
        self.endEditing(true)
        self.saveBtnClosure?()
    }
    
}
